<?php

namespace app\admin\controller\article;

use app\admin\controller\AuthController;
use app\admin\model\system\SystemAttachment;
use services\{
    UtilService as Util, JsonService as Json
};
use app\admin\model\article\{
    ArticleCategory as ArticleCategoryModel, Article as ArticleModel
};
use think\Facade\Request;

/**
 * 图文管理
 * Class WechatNews
 * @package app\admin\controller\wechat
 */
class Article extends AuthController
{

    public function index()
    {

        if (Request::isAjax()) {
            $where = Util::getMore([
                ['page', 1],
                ['limit', 20],
                ['title',''],
                ['cid']
            ]);
            return Json::successlayui(ArticleModel::getList($where));
        }
        $tree = sort_list_tier(ArticleCategoryModel::getArticleCategoryList());
        $this->assign(compact('tree'));
        return $this->fetch();
    }


    
    /**
     * 编辑表单
     * @param $id
     * @return mixed|\think\response\Json|void
     */
    public function form()
    {
        $this->assign('cate_list',sort_list_tier(ArticleCategoryModel::getArticleCategoryList()));
        if($id = Request::param('id/d')){
            $detail = ArticleModel::get($id);
            $this->assign('detail',$detail);
            if (!$detail) return JsonService::fail('数据不存在!');
        }
        return $this->fetch('create');
    }

         /**
     * 表单提交
     *
     * @return json
     */
    public function save(){
        $post_data = Request::post();

        if($post_data['id']){
            $res = ArticleModel::update($post_data);
        }else{
            $res = ArticleModel::add($post_data);
        }
        
        if($res){
             return Json::successful('保存成功');
        }else{
             return Json::fail('保存失败');
        }
    }
    
    /**
     * @name: 表格导出
     * @msg: 
     * @return {json} 
     */
    public function export(){
        $data = ArticleModel::with('cate')->select();
        $data = count($data) ? $data->toArray() : [];
        $count= ArticleModel::count();
        return Json::successlayui(compact('data','count'));
    }

    /**
     * 快速编辑
     *
     * @return json
     */
    public function set_value($field = '', $id = '', $value = '')
    {
        $field == '' || $id == '' || $value == '' && JsonService::fail('缺少参数');
        if (ArticleModel::where(['id' => $id])->update([$field => $value])) {
            return Json::successful('保存成功');
        } else {
            return Json::fail('保存失败');
        }

    }

        /**
     * @name: 删除
     * @Author: Sam
     * @Date: 2020-05-21 16:37:42
     * @msg:
     * @param {type}
     * @return:
     */
    public function del()
    {
        $id = Request::param('id/a'); //转化数组
        !$id && JsonService::fail('缺少参数');
        if (ArticleModel::del($id)) {
            return Json::successful('删除成功');
        } else {
            return Json::fail('删除失败');
        }

    }

}